const connect = require('connect')
const url = require('url')

const posts = {
  'my-post-title': 1
}

const findPostIdBySlug = (str, cb) => {
  if (!str) {
    cb(new Error('str is empty!'))
    return
  }

  cb(null, posts[str])
}

const rewrite = (req, res, next) => {
  const path = url.parse(req.url).pathname
  const match = path.match(/^\/blog\/post\/(.+)/)

  findPostIdBySlug(match[1], (err, id) => {
    if (err) return next(err)
    if (!id) return next(new Error('post not found'))

    req.url = '/blog/posts/' + id
    next()
  })
}

const showPost = (req, res, next) => {
  res.end(req.url)
}

connect()
  .use(rewrite)
  .use(showPost)
  .listen(3000)

/*
curl http://localhost:3000/blog/post/my-post-title
 */
